package com.zero.mongo.transaction;

import com.mongodb.client.*;
import org.bson.Document;

import java.util.Arrays;

/**
 * mongodb transaction
 * 注意：mongodb事务要在集群上才行
 *
 */
public class TransactionTest {
    public static void main( String[] args ) {

        MongoClient mongoClient = MongoClients.create("mongodb://192.168.1.108:27017");

        MongoDatabase db = mongoClient.getDatabase("testdb-tx");

        ClientSession session = mongoClient.startSession();

        try{
            session.startTransaction();

            MongoCollection<Document> member = db.getCollection("t_member");
            Document memberDoc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("versions", Arrays.asList("v3.2", "v3.3", "v.3.4"))
                    .append("info",new Document("x",203).append("y",222));

            member.insertOne(memberDoc);


            /**
             * 制造一个异常
             */
           /* MongoCollection<Document> user = db.getCollection("t_user");
            Document userDoc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1/0)
                    .append("versions", Arrays.asList("v3.2", "v3.3", "v.3.4"))
                    .append("info",new Document("x",203).append("y",222));

            user.insertOne(userDoc);*/

            session.commitTransaction();

        }catch (Exception e){
            //回滚
            session.abortTransaction();
        }finally {
            session.close();
        }

    }
}
